from fastapi import File, UploadFile, Form, HTTPException
from fastapi.routing import APIRouter
from fastapi import Request
from fastapi.templating import Jinja2Templates
from .ocr import general_ocr_recognition
from fastapi import Request
from config import USER_CONFIGS
import json
from fastapi import Body
import os
from fastapi import Body, Query
from models.doubao import ask_model_with_image
# 创建一个APIRouter实例
router = APIRouter()
# 初始化模板引擎，指向templates文件夹
templates = Jinja2Templates(directory="templates")

# 首页
@router.get("/")
async def read_root(request: Request):
    # 返回index.html
    return templates.TemplateResponse("index.html", {"request": request})
   

# 定义一个上传图片的路由
@router.post("/upload/")
async def upload_image(file: UploadFile = File(...), user_key: str = Form(...)):  # 添加user_key参数
    if file.content_type and not file.content_type.startswith('image/'):
        raise HTTPException(status_code=422, detail="仅允许上传图片文件")
    try:
        # 验证用户key是否存在
        if user_key not in USER_CONFIGS:
            raise HTTPException(status_code=400, detail=f"用户{user_key}不存在")
        
        # 写死文件路径
        file_path = os.path.join('upload', 'clip_screenshot.png')
        with open(file_path, "wb") as f:
            contents = await file.read()
            f.write(contents)
        return {"message": "图片已保存到固定路径", "file_path": file_path, "user": user_key}  # 返回用户名
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 定义一个处理图片的路由
@router.post("/recognize-resources")  # 修改路由路径为资源识别相关
async def process_screenshot(user_key: str = Form(...)):  # 只需要user_key参数
    file_path = os.path.join('upload', 'clip_screenshot.png')
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="截图文件不存在")
    
    try:
        # 验证用户key是否存在
        from config import USER_CONFIGS
        if user_key not in USER_CONFIGS:
            raise HTTPException(status_code=400, detail=f"用户{user_key}不存在")
        
        # 向模型提问
        system_prompt = "你是一个部落冲突游戏资源识别助手，你只需要返回数字，用逗号隔开，其他什么也不要返回,如果没有数据，无法回答时全返回0就可以了"
        user_question = "金币，圣水，黑油分别为多少"
        
        # 传递user_id参数
        result = ask_model_with_image(system_prompt, user_question, image_path=file_path, user_id=user_key)
        result_list = ["0", "0", "0"]  # 默认值
        if result:
            print(result)
            # 转换为列表
            result_list = result.split(',')
            print("金币:"+result_list[0])
            print("圣水:"+result_list[1])
            print("黑油:"+result_list[2])
        return {"message": result_list}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 定义一个处理图片的路由
@router.post("/ocr/")
async def ocr_image(request: Request):
    # 1. 获取user_key
    user_key = None
    content_type = request.headers.get("Content-Type", "").lower()

    # 2. 根据不同Content-Type解析请求数据
    if "application/json" in content_type:
        try:
            request_data = await request.json()
            user_key = request_data.get("user_key")
        except json.JSONDecodeError:
            raise HTTPException(status_code=400, detail="无效的JSON格式，请检查请求体")
    elif "application/x-www-form-urlencoded" in content_type:
        form_data = await request.form()
        user_key = form_data.get("user_key")
    else:
        # 3. 尝试从查询参数获取作为备选方案
        query_params = request.query_params
        user_key = query_params.get("user_key")

    # 4. 验证user_key参数
    if not user_key:
        raise HTTPException(status_code=400, detail="未找到user_key参数，请检查请求")

    # 确保user_key是字符串类型
    user_key_str = str(user_key)

    # 5. 验证用户配置
    if user_key_str not in USER_CONFIGS:
        raise HTTPException(status_code=401, detail=f"无效的user_key: {user_key_str}")
    
    # 6. 处理图片路径
    file_path = os.path.join('upload', 'clip_screenshot.png')
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail=f"图片文件不存在: {file_path}")

    # 7. 调用OCR识别
    user_config = USER_CONFIGS[user_key_str]
    result = general_ocr_recognition(file_path, user_config)
    
    # 8. 添加调试信息
    print(f"OCR识别结果: {result}")
    
    # 9. 检查是否包含游戏结束相关文字
    if result and 'words_result' in result:
        # 扩展关键词列表，包括可能的游戏结束提示
        end_game_keywords = ["回营", "返回村庄", "回村", "结束", "胜利", "失败", "VICTORY", "DEFEAT"]
        
        for item in result['words_result']:
            words = item['words']
            print(f"检测到文字: {words}")
            
            # 检查是否包含任何游戏结束关键词
            for keyword in end_game_keywords:
                if keyword in words:
                    print(f"匹配到游戏结束关键词: {keyword}")
                    # 确保返回标准格式
                    response_data = {"result": True}
                    print(f"返回响应: {response_data}")
                    return response_data
    
    print("未匹配到游戏结束关键词")
    # 确保返回标准格式
    response_data = {"result": False}
    print(f"返回响应: {response_data}")
    return response_data

# 获取用户配置
@router.post("/config")  
async def get_user_config(user_key: str = Body(..., media_type="text/plain")):  
    try:  
        if not user_key.strip():  # 去除两端空白后检查
            raise HTTPException(status_code=400, detail="user_key不能为空")
        
        if user_key not in USER_CONFIGS:  # 这里假设USER_CONFIGS是已定义的用户配置字典
            raise HTTPException(status_code=400, detail=f"用户{user_key}不存在")
        
        return {"user_config": USER_CONFIGS[user_key]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户配置失败: {str(e)}")



# 修改用户配置
@router.post("/config/update/")  # 注意这里添加了尾随斜杠
def update_user_config(
    user_key: str = Query(..., description="用户标识"),
    config_group: str = Query(..., description="配置组名称，如 'openai', 'baidu_ocr'"),
    config_key: str = Query(..., description="配置项名称，如 'base_url', 'api_key'"),
    new_value: str = Query(..., description="新的配置值")
):
    try:
        # 检查用户是否存在
        if user_key not in USER_CONFIGS:
            raise HTTPException(status_code=400, detail=f"用户{user_key}不存在")

        # 检查配置组是否存在
        if config_group not in USER_CONFIGS[user_key]:
            raise HTTPException(status_code=400, detail=f"配置组{config_group}不存在")

        # 初始化旧值变量
        old_value = None

        # 特殊处理phone_configs组
        if config_group == "phone_configs":
            # 对于phone_configs，config_key是手机型号，new_value是整个配置的JSON字符串
            import json
            try:
                # 保存旧值
                old_value = USER_CONFIGS[user_key][config_group][config_key]
                parsed_value = json.loads(new_value)
                USER_CONFIGS[user_key][config_group][config_key] = parsed_value
            except json.JSONDecodeError:
                raise HTTPException(status_code=400, detail="无效的JSON格式")
        else:
            # 检查配置项是否存在
            if config_key not in USER_CONFIGS[user_key][config_group]:
                raise HTTPException(status_code=400, detail=f"配置项{config_key}不存在于{config_group}中")

            # 保存旧值用于日志
            old_value = USER_CONFIGS[user_key][config_group][config_key]

            # 尝试解析JSON字符串，如果是对象类型的话
            import json
            try:
                # 如果是JSON对象字符串，解析后保存
                if new_value.strip().startswith('{') and new_value.strip().endswith('}'):
                    parsed_value = json.loads(new_value)
                    USER_CONFIGS[user_key][config_group][config_key] = parsed_value
                else:
                    # 否则保存为原始字符串
                    USER_CONFIGS[user_key][config_group][config_key] = new_value
            except json.JSONDecodeError:
                # 如果解析失败，保存为原始字符串
                USER_CONFIGS[user_key][config_group][config_key] = new_value

        # 持久化保存到文件
        save_config_to_file()

        # 返回成功响应
        return {
            "status": "success",
            "message": f"用户{user_key}的{config_group}.{config_key}配置已更新",
            "old_value": old_value,
            "new_value": new_value
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"修改用户配置失败: {str(e)}")

# 保存配置到文件
def save_config_to_file():
    import json
    import os

    # 获取config.py文件路径
    config_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config.py')

    # 读取原始文件内容
    with open(config_file_path, 'r', encoding='utf-8') as f:
        original_content = f.read()

    # 找到USER_CONFIGS的起始和结束位置
    start_marker = 'USER_CONFIGS = '
    start_index = original_content.find(start_marker) + len(start_marker)
    
    # 找到USER_CONFIGS的结束位置（需要找到最后一个大括号）
    brace_count = 0
    end_index = start_index
    for i in range(start_index, len(original_content)):
        if original_content[i] == '{':
            brace_count += 1
        elif original_content[i] == '}':
            brace_count -= 1
            if brace_count == 0:
                end_index = i + 1
                break

    # 生成新的配置内容，使用自定义格式化函数保持Python字典格式
    def format_dict(d, indent=0):
        """格式化字典为Python代码格式"""
        if isinstance(d, dict):
            if not d:
                return '{}'
            indent_str = '    ' * indent
            next_indent_str = '    ' * (indent + 1)
            items = []
            for k, v in d.items():
                key_str = f'"{k}"' if isinstance(k, str) else str(k)
                if isinstance(v, dict):
                    value_str = format_dict(v, indent + 1)
                elif isinstance(v, str):
                    value_str = f'"{v}"'
                else:
                    value_str = str(v)
                items.append(f'{next_indent_str}{key_str}: {value_str}')
            return '{\n' + ',\n'.join(items) + '\n' + indent_str + '}'
        else:
            return str(d)

    config_str = format_dict(USER_CONFIGS, 0)

    # 构建新的文件内容
    new_content = original_content[:start_index] + config_str + original_content[end_index:]

    # 写入文件
    with open(config_file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)

    
      


